<!-- ZmUpload -->
<template>
  <van-uploader
    ref="uploader"
    :multiple="multiple"
    :preview-image="previewImage"
    :after-read="afterRead"
    v-model="fileList"
    v-bind="$attrs"
  >
    <slot></slot>
  </van-uploader>
</template>

<script>
//  @success  上传成功
//  @error 上传失败
import oss from '@/utils/src/aliOss';
import lrz from 'lrz';
import PhotoCompress from '@/utils/src/compress';
export default {
  name: 'ZmUpload',
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    previewImage: {
      type: Boolean,
      default: true
    },
    // 是否压缩
    lrz: {
      type: Boolean,
      default: true
    },// 客户自定义压缩
    customCompress: {
      type: Boolean,
      default: true
    },
    cpMaxSize: {
      type: Number,
      default: 0.5 * 1024 * 1024
    },
     cpMinSize: {
      type: Number,
      default: 0.001 * 1024 * 1024
    },
    value: {
      type: String
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    value(value) {
      if (value) {
        const imgArray = value.split(',').filter(i => i);
        // console.log('imgArray',imgArray);
        this.fileList = imgArray.map(i => {
          return { url: i };
        });
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化方法
    init() {
      this.initData();
    },
    initData() {
      if (this.value) {
        const imgArray = this.value.split(',').filter(i => i);
        console.log('imgArray', imgArray);
        this.fileList = imgArray.map(i => {
          return { url: i };
        });
      }
    },
    // 选择文件
    chooseFile() {
      this.$refs.uploader.$el.getElementsByTagName('input')[0].click();
    },
    // 读取文件钩子
    afterRead(files) {
      let _files = [];
      if (files.length) {
        _files = files.map(i => i.file);
      } else {
        _files = [files.file];
      }
      _files.forEach(i => {
        this.upload(i);
      });
    },

    // 图片上传
    async upload(file) {
      this.$msg.loading('');
      let vm = this;
      // let _file = file;
      // try {
      //   _file = await this.handleLrz(file);
      // } catch (error) {
      //   console.log(error, '压缩失败传源文件');
      // }
      console.log(file);
      // const formData = new FormData();
      // formData.append('image', _file);
      if (file.type.indexOf('image') > -1 && this.customCompress && (file.size > vm.cpMaxSize)) {
        // 压缩到500k以内
        var photoCompress = new PhotoCompress(vm.cpMinSize, vm.cpMaxSize);
        photoCompress.compress(file, async function(_file) {
          console.log('压缩后大小', _file.size);
          vm.uploadApi(_file);
        });
      } else {
        if (file.size > 20 * 1024 * 1024) {
          this.$msg.showMsg('文件不能超过20M!');
          return;
        }
        vm.uploadApi(file);
      }
    },
    async uploadApi(_file) {
      try {
        let res = await oss.put(_file.name, _file);
        console.log('file', res);
        const url = res.url;
        this.fileList.push({ url });
        this.fileList = this.fileList.filter(i => i.url);
        this.$emit('success', res);
        this.$msg.hide();
      } catch (err) {
        this.$msg.hide();
        this.$emit('error', err);
        this.fileList = this.fileList.filter(i => i.url);
      }
    },
    handleLrz(file) {
      if (!this.lrz) {
        return Promise.resolve(file);
      }
      // 大于 300k 压缩
      const quality = file.size / 1024 > 500 ? 0.8 : 1;
      if (quality === 1) {
        return Promise.resolve(file);
      }
      return lrz(file, { quality }).then(rst => {
        console.log('压缩后', rst);
        rst.file.name = rst.origin.name;
        return rst.file;
      });
    },

    getImgUrl() {
      const imgArray = this.fileList
        .filter(i => i.url)
        .map(i => i.url)
        .join(',');
      this.$emit('input', imgArray);
      return imgArray;
    }
  }
};
</script>
<style lang="scss" scoped></style>
